module.exports = (EdtApi) => {
    "use strict";
    let chatId = "", count = 0, badges, iframe, leftIframe;
    function isGroup() {
        return window.location.href?.includes("/space/");
    }
    async function getChatId(times = 0) {
        let url = window.location.href;
        let id = url.substring(url.lastIndexOf("/") + 1);
        if ("home" == id) {
            let headEl = iframe.contentDocument.querySelector("c-wiz div[data-soft-view-id]");
            let text = headEl?.getAttribute("data-soft-view-id") || "";
            if (text) {
                id = text.substring(text.lastIndexOf("/") + 1);
            } else id = "";
        }
        if (id && id != chatId) return id;
        await EdtApi.sleep(50);
        if (times > 10) return id;
        times++;
        return getChatId(times);
    }
    function closest(element, selector, level = 0) {
        let result = null, count = 0;
        while (element && element !== iframe?.contentDocument) {
            if (element.matches(selector)) {
                result = element;
                break;
            }
            count++;
            element = element.parentNode;
            if (level > 0 && count >= level) {
                break;
            }
        }
        return result;
    }
    return {
        config: {
            friendList: '#talk_roster',
            chat: 'body c-wiz[jsrenderer="MhqlIf"]',
            input: 'div.tAVIoc.I9OJHe>div.editable[role="textbox"]',
            msgBox: 'div.auHzcc.cFc9ae[jsname="FbxuNe"]',
            sendBtn: 'div.I0LFzc.mS1Rod button.VYBDae-Bz112c-LgbsSe[jsname="GBTyxb"]',
            setting: 'div.AYGmkd.fb0g6>div[jsname="AAsgyb"]',
            inputType: "input",
            autoCount: 20
        },
        init(handle) {
            this.initMain(handle);
            this.initOther(handle);
        },
        initMain(handle) {
            EdtApi.queryWait({
                selector: 'div.nH.bkK div.aeF>div.nH div[role="main"] iframe.bGz',
                timeout: 60000
            }).then(mainIframe => {
                if (!mainIframe) return;
                mainIframe.onload = function () {
                    let btn;
                    if (!mainIframe.getAttribute("init-event")) {
                        mainIframe?.contentDocument?.addEventListener("click", e => {
                            iframe = mainIframe;
                            btn = closest(e.target, 'div.Kbjimc.krjOGe[jsname="WhB0mf"]', 20);
                            if (btn) handle.initChat(null);
                        });
                        handle.initEventListener(mainIframe?.contentDocument);
                        mainIframe.setAttribute("init-event", 1);
                    }
                };
            });
        },
        initOther(handle) {
            EdtApi.queryWait({
                selector: 'div.nH.bkK div.aeF>div.nH iframe[name="single_full_screen"]',
                timeout: 60000
            }).then(singleIframe => {
                if (!singleIframe) return;
                iframe = singleIframe;
                singleIframe.onload = function () {
                    if (!singleIframe.getAttribute("init-event")) {
                        let btn = singleIframe?.contentDocument?.querySelector("div.DWWcKd-OomVLb-LgbsSe>div.XXAR0");
                        btn?.removeEventListener("click", handle.initChat);
                        btn?.addEventListener("click", handle.initChat);
                        handle.initEventListener(singleIframe?.contentDocument);
                        singleIframe.setAttribute("init-event", 1);
                    }
                    let observer = new MutationObserver(() => {
                        // console.log(opts);
                        iframe = singleIframe;
                        handle.initChat(null);
                    });
                    observer?.observe(singleIframe?.contentDocument.body, {
                        childList: true,
                        subtree: false
                    });
                };
            });
        },
        injectCss() {
            let styles = iframe?.contentDocument?.getElementById(`style-${chatId}`);
            if (styles) return;
            let head = iframe?.contentDocument?.querySelector("head");
            if (!head) return;
            styles = document.createElement('style');
            styles.id = `#style-${chatId}`;
            styles.innerHTML = EdtApi.readFileSync(`${__dirname}/webview.css`) || "";
            head.append(styles);
        },
        setStyle(styleStr) {
            let style = iframe?.contentDocument?.getElementById('ed-trans-style');
            if (!style) {
                let head = iframe?.contentDocument?.querySelector("head");
                if (!head) return;
                style = document.createElement('style');
                style.setAttribute("id", 'ed-trans-style');
                head.append(style);
            }
            if (!style) return;
            style.innerHTML = styleStr;
        },
        getChatEl() {
            if (!iframe) return null;
            let chat = iframe?.contentDocument?.querySelector(this.config.chat);
            return chat;
        },
        getInputEl() {
            if (!iframe) return null;
            let inputEl = iframe?.contentDocument?.querySelector(this.config.input);
            return inputEl;
        },
        getMsgBox() {
            if (!iframe) return null;
            let box = iframe?.contentDocument?.querySelector(this.config.msgBox);
            return box;
        },
        getPlaceholderEl(chatEl) {
            return chatEl.querySelector('div.tAVIoc.I9OJHe>div.GB6BTc.snByac[jsname="V67aGc"]');
        },
        getTipsOutEl(chatEl) {
            if (!iframe) return null;
            let tipsOutEl = iframe?.contentDocument?.querySelector('div.byY7Yb.cFc9ae[jsname="SFaVIf"]>div.edt-tips-out');
            if (!tipsOutEl) {
                let outBox = chatEl.querySelector('div.byY7Yb.cFc9ae[jsname="SFaVIf"]');
                if (outBox) {
                    tipsOutEl = document.createElement("div");
                    tipsOutEl.classList.add("edt-tips-out");
                    tipsOutEl.innerHTML = `<div class="tips-msg"></div>`;
                    outBox?.append(tipsOutEl);
                }
            }
            return tipsOutEl;
        },
        getTipsInEl(chatEl) {
            if (!iframe) return null;
            let tipsInEl = iframe?.contentDocument?.querySelector('div.HrE5Tb.SexRqd>div.edt-tips-in');
            if (!tipsInEl) {
                let inBox = chatEl.querySelector('div.HrE5Tb.SexRqd>div[role="button"]');
                if (inBox) {
                    tipsInEl = document.createElement("div");
                    tipsInEl.classList.add("edt-tips-in");
                    tipsInEl.innerHTML = `<div class="trans-config"></div>`;
                    inBox?.after(tipsInEl);
                }
            }
            return tipsInEl?.querySelector(".trans-config");
        },
        getAllMsg(box) {
            return box?.querySelectorAll('div.SvOPqd>c-wiz div.Zc1Emd.QIJiHb');
        },
        getMessageList(box) {
            let allMsg = box?.querySelectorAll('div.SvOPqd>c-wiz div.Zc1Emd.QIJiHb:not(.trans-inited)');
            let msgList = {
                in: [],
                out: []
            };
            allMsg?.forEach(msg => {
                if (closest(msg, "div.Pxe3Yd")) {
                    msgList.out.push(msg);
                } else msgList.in.push(msg);
            });
            return msgList;
        },
        getUnread() {
            count = 0;
            if (!leftIframe) leftIframe = document.getElementById("gtn-roster-iframe-id");
            badges = leftIframe?.contentDocument?.querySelectorAll('c-wiz div.RuSDjb>div.zY9JEf.TeR7uc');
            badges?.forEach(badge => {
                count += EdtApi.safeParseInt(badge.textContent);
            });
            return count;
        },
        getChatInfo() {
            return new Promise(async (resolve) => {
                chatId = await getChatId();
                this.injectCss();
                let chatEl = this.getChatEl();
                console.log("chatId:", chatId, chatEl);
                resolve({ id: chatId, isGroup: isGroup(), chatEl });
            });
        },
        getChatTitle(chatEl = iframe?.contentDocument) {
            let titleEl = chatEl.querySelector('div.Bqp03e>c-wiz span.wWf0Bc.ojqkvd,div.Bqp03e>c-wiz span.njhDLd.O5OMdc');
            return titleEl?.textContent || "";
        },
        getText(msgBox) {
            if (!msgBox) return '';
            let text = '';
            try {
                if (!msgBox.querySelector('img[data-emoji]')) {
                    text = msgBox.textContent;
                } else {
                    msgBox.childNodes?.forEach(child => {
                        if (child.nodeName == '#text') {
                            text += child.textContent;
                        } else if (child.nodeName == 'IMG') {
                            text += child.getAttribute("alt") || "";
                        } else if (child.nodeName == "BR") {
                            text += '\n';
                        }
                    });
                }
            } catch (error) {
                console.error(error);
            }
            return text;
        },
        getIptMsg(inputEl) {
            if (!inputEl) return "";
            let value = "";
            try {
                value = inputEl.textContent;
                if (!value) return "";//纯表情不翻译
                value = "";
                inputEl.childNodes?.forEach((child) => {
                    if (child.nodeName == "#text") {
                        value += child.textContent;
                    } else if (child.nodeName == "IMG") {
                        value += child.alt;
                    } else if (child.nodeName == "BR") {
                        value += "\n";
                    }
                });
            } catch (error) {
                console.error(error);
            }
            return value;
        },
        getUserInfo() {
            try {
                let userEl = document.querySelector("header a.gb_A.gb_Xa.gb_Z");
                let avatarEl = userEl?.querySelector("img");
                let avatar = avatarEl?.getAttribute("src") || "";
                let userInfo = userEl?.getAttribute("aria-label") || "";
                let userName = "";
                let account = "";
                if (userInfo?.includes("：")) {
                    userInfo = userInfo.split("：")[1];
                }
                if (userInfo?.includes(":")) {
                    userInfo = userInfo.split(":")[1];
                }
                if (userInfo?.includes("(")) {
                    let strs = userInfo.split("(");
                    userName = strs[0]?.trim();
                    account = strs[1]?.trim()?.replace(")", "");
                }
                return {
                    avatar,
                    userName,
                    account,
                    toDataUrl: true
                };
            } catch (error) {
                console.error(error);
                return null;
            }
        }
    }
};